 

const openaiApiKey = "sk-01JdZXYQTPM0xpZbD9Bc20B48d18448c82B9C8Af008dE58e";
const openaiApiUrl = 'https://api.midjourneye.com/v1/chat/completions';
interface TokenUsage {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
    prompt_tokens_details: Record<string, unknown>;
    completion_tokens_details: Record<string, unknown>;
  }
export async function* chatStream(message:string,ref:{current:any}) :AsyncGenerator<string,TokenUsage|undefined,unknown>{
    let response;
    try{
         response = await fetch(openaiApiUrl, {
        method: 'POST',
        headers: {
            'x-api-key': 'YOUR_API_KEY',
            'anthropic-version': '2023-06-01',
            'content-type': 'application/json',
            "Authorization": `Bearer ${openaiApiKey}`
        },
        body: JSON.stringify({
            model: 'claude-3-5-sonnet-20241022',
            messages: [{
                role: 'user',
                content: message
            }],
            max_tokens: 8000,
            stream: true
        })
    });
    }catch(e){
        console.log(e);
        return;
    }
     
    if(!response||response.body===null){
        return;
    }
    const reader = response.body.getReader();
    const decoder = new TextDecoder(); 
    try {
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            
            const chunk = decoder.decode(value);
            const lines = chunk.split('\n').filter(line => line.trim());
            
            for (const line of lines) {
                if (line.includes('data: ')) {
                    const data = line.replace('data: ', '');  
                    if(data=='[DONE]'){
                        continue; 
                    }                
                    try {
                        const parsed = JSON.parse(data);
                        if(parsed.usage){                           
                            ref.current=parsed.usage;                                                 
                        }
                        yield parsed.choices[0];
                    } catch (e) {
                        console.error('Failed to parse chunk:', e);
                    }
                }
            }
        }
    } finally {
        reader.releaseLock();
    }
    
}

     
 

